<!-- 正文开始 -->
<div class="layui-fluid">
    <div class="layui-card">
        <div class="layui-card-body">
            <!-- 头部操作栏 -->
            <div class="layui-form lay-header">
                <div class="toolbar">
                    <div class="layui-form-item lay-query-content">
                        <div class="lay-query-box">
                            <div class="query-lt">
                                <div class="layui-inline">
                                    <label class="layui-form-label w-auto">代理商名称：</label>
                                    <div class="layui-input-inline">
                                        <input name="name" class="layui-input" type="text"
                                               placeholder="请输入代理商名称"/>
                                    </div>
                                </div>
                                <div class="layui-inline">
                                    <label class="layui-form-label w-auto">营业执照号：</label>
                                    <div class="layui-input-inline">
                                        <input name="licenseNo" class="layui-input" type="text"
                                               placeholder="请输入营业执照号"/>
                                    </div>
                                </div>
                                <div class="layui-inline">
                                    <button class="layui-btn icon-btn color-green" lay-filter="formSubSearchLog" layui-form-keyDownSearch="true" lay-submit>查询</button>
                                    <button class="layui-btn icon-btn color-white" lay-filter="resets" lay-submit>重置</button>
                                </div>
                            </div>
                            <div class="query-rt"></div>
                        </div>
                    </div>
                </div>
                <div class="lay-btn-rows">
                    <div class="lay-btn-box">
                        <div class="lay-btn-lt">
                            <button id="agentBtnAdd" class="layui-btn icon-btn color-reseda">添加
                            </button>
                            <button id="agentBtnExport" class="layui-btn icon-btn color-reseda">导出
                            </button>
                        </div>
                    </div>
                </div>
            </div>
            <!-- 表格 -->
            <table class="layui-table" id="agentTable" lay-filter="agentTable"></table>
        </div>
    </div>
</div>

<!-- 表格操作列 -->
<script type="text/html" id="agentTableBar">
    <a class="layui-btn layui-btn-warm layui-btn-xs" lay-event="edit">修改</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
    <a class="layui-btn layui-btn-xs" lay-event="subjectList">尽调</a>
    {{# if(d.status=='wait_check'){  }}
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="applyCheck">审核</a>
    {{# } }}
</script>

<!-- 表单弹窗 -->
<script type="text/html" id="agentForm">
    <form lay-filter="agentForm" class="layui-form model-form">
        <input name="id" type="hidden"/>
        <div class="layui-col-xs6">
            <div class="layui-form-item">
                <label class="layui-form-label" style="width: 100px">代理商名称</label>
                <div class="layui-input-block" style="margin-left: 130px">
                    <input name="name" placeholder="代理商名称" type="text" class="layui-input" lay-verify="required"
                           required/>
                </div>
            </div>
        </div>
        <div class="layui-col-xs6">
            <div class="layui-form-item">
                <label class="layui-form-label" style="width: 100px">营业执照号</label>
                <div class="layui-input-block" style="margin-left: 130px">
                    <input name="licenseNo" placeholder="请输入营业执照号" type="text" class="layui-input"
                           lay-verify="required" required/>
                </div>
            </div>
        </div>
        <div class="layui-col-xs6">
            <div class="layui-form-item">
                <label class="layui-form-label" style="width: 100px">营业执照照片</label>
                <div id="btnUpload14" class="layui-btn" style="float: left;"><i class="layui-icon">&#xe681;</i>上传图片
                </div>
                <div id="btnUpload14_path" style="margin-left: 260px;line-height: 40px;"></div>
                <input id="licensePhoto" name="licensePhoto" type="hidden"/>
            </div>
        </div>
        <div class="layui-col-xs6">
            <div class="layui-form-item">
                <label class="layui-form-label" style="width: 100px">开户许可证</label>
                <div id="btnUpload15" class="layui-btn" style="float: left;"><i class="layui-icon">&#xe681;</i>上传图片
                </div>
                <div id="btnUpload15_path" style="margin-left: 260px;line-height: 40px;"></div>
                <input id="openingPermit" name="openingPermit" type="hidden"/>
            </div>
        </div>
        <div class="layui-col-xs6">
            <div class="layui-form-item">
                <label class="layui-form-label" style="width: 100px">代理商所属级别</label>
                <div class="layui-input-block" style="margin-left: 130px">
                    <select lay-filter="agtLevel" id="agtLevel" name="agtLevel" lay-verify="required">
                        <option value="">请选择物料类型</option>
                    </select>
                </div>
            </div>
        </div>
        <div class="layui-col-xs6">
            <div class="layui-form-item">
                <label class="layui-form-label" style="width: 100px">省</label>
                <div class="layui-input-block" style="margin-left: 130px">
                    <select name="provinceId" id="provinceId" lay-filter="provinceId" lay-verify="required"
                            required></select>
                </div>
            </div>
        </div>
        <div class="layui-col-xs6">
            <div class="layui-form-item">
                <label class="layui-form-label" style="width: 100px">市</label>
                <div class="layui-input-block" style="margin-left: 130px">
                    <select name="cityId" id="cityId" lay-filter="cityId" lay-verify="required" required></select>
                </div>
            </div>
        </div>
        <div class="layui-col-xs6">
            <div class="layui-form-item">
                <label class="layui-form-label" style="width: 100px">区/县</label>
                <div class="layui-input-block" style="margin-left: 130px">
                    <select name="areaId" id="areaId" lay-filter="areaId" lay-verify="required" required></select>
                </div>
            </div>
        </div>
        <div class="layui-col-xs6">
            <div class="layui-form-item">
                <label class="layui-form-label" style="width: 100px">详细地址</label>
                <div class="layui-input-block" style="margin-left: 130px">
                    <input name="addr" placeholder="请输入详细地址" type="text" class="layui-input"
                           lay-verify="required"
                           required/>
                </div>
            </div>
        </div>
        <div class="layui-col-xs6">
            <div class="layui-form-item">
                <label class="layui-form-label" style="width: 100px">收款银行名</label>
                <div class="layui-input-block" style="margin-left: 130px">
                    <input name="bankName" placeholder="请输入收款银行名" type="text" class="layui-input"
                           lay-verify="required" required/>
                </div>
            </div>
        </div>
        <div class="layui-col-xs6">
            <div class="layui-form-item">
                <label class="layui-form-label" style="width: 100px">收款银行户名</label>
                <div class="layui-input-block" style="margin-left: 130px">
                    <input name="bankAccount" placeholder="请输入收款银行户名" type="text" class="layui-input"
                           lay-verify="required" required/>
                </div>
            </div>
        </div>
        <div class="layui-col-xs6">
            <div class="layui-form-item">
                <label class="layui-form-label" style="width: 100px">收款银行号码</label>
                <div class="layui-input-block" style="margin-left: 130px">
                    <input name="bankCard" placeholder="请输入收款银行号码" type="text" class="layui-input"
                           lay-verify="required" required/>
                </div>
            </div>
        </div>
        <div class="layui-col-xs6">
            <div class="layui-form-item">
                <label class="layui-form-label" style="width: 100px">代理商来源</label>
                <div class="layui-input-block" style="margin-left: 130px">
                    <select name="sourceId">
                        <option value="admin">后台录入</option>
                    </select>
                </div>
            </div>
        </div>
        <div class="layui-col-xs6">
            <div class="layui-form-item">
                <label class="layui-form-label" style="width: 100px">代理商类型</label>
                <div class="layui-input-block" style="margin-left: 130px">
                    <select name="type">
                        <option value="on">签约渠道</option>
                        <option value="having">意向渠道</option>
                    </select>
                </div>
            </div>
        </div>
        <div class="layui-col-xs6">
            <div class="layui-form-item">
                <label class="layui-form-label" style="width: 100px">对接人</label>
                <div class="layui-input-block" style="margin-left: 130px">
                    <input name="counterpart" placeholder="请输入对接人" type="text" class="layui-input"
                           lay-verify="required" required/>
                </div>
            </div>
        </div>
        <div class="layui-col-xs6">
            <div class="layui-form-item">
                <label class="layui-form-label" style="width: 100px">代理商分类</label>
                <input name="agentCategoryId" value="" type="hidden">
                <div class="layui-input-block" style="margin-left: 130px">
                    <div class="layui-input-inline mr0" id="agentCategoryId" style="width: 313px;">
                    </div>
                </div>
            </div>
        </div>
        <div class="layui-form-item text-right">
            <button class="layui-btn layui-btn-primary" type="button" ew-event="closeDialog">取消</button>
            <button class="layui-btn" lay-filter="agentFormSubmit" lay-submit>保存</button>
        </div>
    </form>
</script>

<style>
    /*尽调样式*/
    div[lay-id="addDueTable"] .layui-table-box,
    div[lay-id="addDueTable"] .layui-table-body,
    div[lay-id="addDueTable"] .layui-table-cell {
        overflow: visible;
        padding: 0 1px;
    }

    div[lay-id="addDueTable"] .layui-table-cell {
        height: auto;
        padding: 0 10px;
        word-break: break-word;
        white-space: pre-line;
    }

    .subjectDetailBox > div {
        margin-right: 10px !important;
    }

    [lay-filter="addDueForm"] .open-details-box::-webkit-scrollbar {
        display: none;
        width: 0;
    }
</style>
<!--尽调管理div-->
<div id="jd">
    <!-- 尽调弹窗 -->
    <script type="text/html" id="dueForm">
        <form lay-filter="dueForm" class="layui-form model-form"
              style="padding: 5px 30px 0 30px;height: calc(100% - 5px);overflow: hidden;">
            <div class="open-details-box"
                 style="height: calc(100% - 100px); padding-top: 20px;overflow: auto;margin-bottom: 20px">
                <div class="layui-form-item">
                    <button id="dueBtnAdd" class="layui-btn icon-btn" type="button">添加客户尽调记录信息</button>
                </div>
                <div class="layui-form-item">
                    <!-- 表格 -->
                    <table class="layui-table" id="dueTable" lay-filter="dueTable"></table>
                </div>
            </div>
            <div class="layui-form-item text-right">
                <button class="layui-btn layui-btn-primary" type="button" ew-event="closeDialog">取消</button>
            </div>
        </form>
    </script>


    <!--尽调添加弹窗 -->
    <script type="text/html" id="addDueForm">
        <form lay-filter="addDueForm" class="layui-form model-form"
              style="padding: 5px 30px 0 30px;height: calc(100% - 5px);overflow: hidden;">
            <div class="open-details-box"
                 style="height: calc(100% - 70px);overflow: auto;margin-bottom: 15px;">
                <div class="layui-form-item">
                    <table class="layui-table" id="addDueTable" lay-filter="addDueTable"
                           style="margin: 0"></table>
                </div>
            </div>
            <div class="layui-form-item text-right">
                <button class="layui-btn layui-btn-primary" type="button" ew-event="closeDialog">取消</button>
                <button id="dueFormSubmit" class="layui-btn" lay-filter="addDueFormSubmit" lay-submit>保存
                </button>
            </div>
        </form>
    </script>


    <!--尽调title-->

    <script type="text/html" id="addDueFormToolbar">
        <a class="layui-btn" lay-event="addDueFormToolbarAdd">添加</a>
    </script>

    <!-- 表格操作列 -->
    <script type="text/html" id="dueTableBar">

        {{# if(d.status=='oncheck'){  }}
        <a class="layui-btn layui-btn-xs" lay-event="dueEdit">修改</a>
        <a class="layui-btn layui-btn-warm layui-btn-xs" lay-event="dueCheck">审核</a>
        <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="dueDel">删除</a>
        {{# }else{ }}
        <a class="layui-btn layui-btn-xs" lay-event="dueDetail">详情</a>
        {{# } }}

    </script>

    <script type="text/html" id="addDueTableBar">
        <a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="del">删除</a>
    </script>
</div>

<!-- js部分 -->
<script>
    layui.use(['layer', 'form', 'table', 'admin',
        'layedit', 'tableTreeDj', 'newTree', 'laydate', 'upload'], function () {
        var $ = layui.jquery;
        var layer = layui.layer;
        var form = layui.form;
        var table = layui.table;
        var config = layui.config;
        var admin = layui.admin;
        var layedit = layui.layedit;
        var upload = layui.upload;
        var tableTree = layui.tableTreeDj;
        var newTree = layui.newTree;
        var laydate = layui.laydate;
        var upload = layui.upload;

        // 渲染表格
        var insTb = table.render({
            elem: '#agentTable',
            url: config.base + 'enterprise/sell/admin/agentApply/list',
            toolbar: true,
            defaultToolbar: ["filter"],
            page: true,
            cellMinWidth: 100,
            cols: [[
                {type: 'checkbox'}
                , {field: 'name', align: 'center', title: '代理商名称'}
                , {field: 'licenseNo', align: 'center', title: '营业执照号', width: 150}
                , {field: 'agtLevelName', align: 'center', title: '所属级别'}
                , {field: 'provinceName', align: 'center', title: '省份'}
                , {field: 'sourceIdDesc', align: 'center', title: '代理商来源'}
                , {field: 'typeDesc', align: 'center', title: '代理商类型'}
                , {field: 'counterpart', align: 'center', title: '对接人'}
                , {field: 'agentCategoryName', align: 'center', title: '代理商分类'}
                , {field: 'statusDesc', align: 'center', title: '代理商状态'}
                , {field: 'createTime', align: 'center', title: '创建时间', width: 170}
                , {align: 'center', toolbar: '#agentTableBar', title: '操作', width: 260}
            ]],
            done: function (res, curr, count) {
                //移除按钮
                var menuButton = config.getMenuButton(location.hash);
                if (menuButton.indexOf("搜索") == -1) {
                    $('.layui-form.toolbar').remove();
                }
                if (menuButton.indexOf("修改") == -1) {
                    $("[lay-event='edit']").remove();
                }
                if (menuButton.indexOf("删除") == -1) {
                    $("[lay-event='del']").remove();
                }
            }
        });

        // 工具条点击事件
        table.on('tool(agentTable)', function (obj) {
            var data = obj.data;
            if (obj.event === 'edit') { //修改
                showEditModel(data);
            } else if (obj.event === 'del') { // 删除
                doDelete(obj);
            } else if (obj.event === 'applyCheck') { // 审核
                doCheck(obj);
            } else if (obj.event === 'subjectList') { // 尽调
                doSubjectList(obj);
            }
        });

        //监听排序
        table.on('sort(agentTable)', function (obj) {
            table.reload('agentTable', {
                initSort: obj
                , where: {
                    sort: obj.field
                    , order: obj.type
                }
            });
        });

        // 搜索
        form.on('submit(formSubSearchLog)', function (data) {
            insTb.reload({where: data.field, page: {curr: 1}}, 'data');
        });

        // 重置搜索
        form.on('submit(resets)', function (data) {
            $(".lay-header").find('select').val("");
            $(".lay-header").find('input').val("");
            let field = data.field;
            for (let key in field) {
                field[key] = ''
            }
            insTb.reload({where: field, page: {curr: 1}}, 'data');
        });

        // 添加按钮点击事件
        $('#agentBtnAdd').click(function () {
            showEditModel();
        });

        /**
         * 加载地址HTML
         * @param data 下拉菜单数据
         * @param tips select 默认提示
         * @param htmltarget html要插入的位置
         * @param name  下拉框需要显示值的属性
         */
        function loadSelectHtml(data, tips, htmltarget, name) {
            let html = ' <option value>' + tips + '</option>';
            if (!data || data == null) {
                return;
            }
            for (let i = 0; i < data.length; i++) {
                let isFinalCategory = '';
                if (data[i].isFinalCategory != undefined) {
                    isFinalCategory = `isFinal=` + data[i].isFinalCategory;
                }
                html += `<option value='${data[i].id}' ${isFinalCategory}>${data[i][name]}</option>`;
            }
            $("[name='" + htmltarget + "']").html(html);
            form.render();
        }

        // 显示编辑弹窗
        function showEditModel(data) {
            admin.open({
                type: 1,
                area: '920px',
                offset: '65px',
                title: data ? '修改销售代理商经销记录' : '添加销售代理商经销记录',
                content: $('#agentForm').html(),
                success: function () {

                    //查询企业信息
                    var enterpriseInfo;
                    admin.req('enterprise/system/admin/enterpricceId/getEnterpricceIdVO', {}, function (res) {
                        enterpriseInfo = res.data;
                    }, 'get', false);
                    if ("" == enterpriseInfo || null == enterpriseInfo) {
                        layer.msg("企业信息获取异常", {icon: 1});
                        return;
                    }

                    //上传代理商营业执照
                    upload.render({
                        elem: '#btnUpload14'
                        , url: config.upload_url + 'uploadFile'
                        , data: {"path": enterpriseInfo.enterpriseCode + "/"}
                        , accept: 'file'
                        , exts: 'jpg|png|RAR|zip|pdf|txt|doc|docx|xls|xlsx|ppt|pptx'
                        , headers: {Authorization: 'Bearer ' + config.getToken()}
                        , done: function (res) {
                            if (res.code == 200) {
                                layer.msg(res.msg, {icon: 1});
                                var imagUrl = res.data.url;
                                // if(imagUrl){
                                //     imagUrl=imagUrl.substring(imagUrl.indexOf('/')+1)
                                // }
                                $('#btnUpload14_path').html('<img src="' + imagUrl + '" style="height: 50px;" />');
                                $('#licensePhoto').val(imagUrl);
                            } else if (res.code == 502) {
                                return location.replace('admin/login.html');
                            } else {
                                layer.msg(res.msg, {icon: 2});
                            }
                        }
                    });
                    if (data && data.licensePhoto) {
                        $('#btnUpload14_path').html('<img src="' + data.licensePhoto + '" style="height: 50px;" />');
                    }

                    //上传开户许可证
                    upload.render({
                        elem: '#btnUpload15'
                        , url: config.upload_url + 'uploadFile'
                        , data: {"path": enterpriseInfo.enterpriseCode + "/"}
                        , accept: 'file'
                        , exts: 'jpg|png|RAR|zip|pdf|txt|doc|docx|xls|xlsx|ppt|pptx'
                        , headers: {Authorization: 'Bearer ' + config.getToken()}
                        , done: function (res) {
                            if (res.code == 200) {
                                layer.msg(res.msg, {icon: 1});
                                var imagUrl = res.data.url;
                                // if(imagUrl){
                                //     imagUrl=imagUrl.substring(imagUrl.indexOf('/')+1)
                                // }
                                $('#btnUpload15_path').html('<img src="' + imagUrl + '" style="height: 50px;" />');
                                $('#openingPermit').val(imagUrl);
                            } else if (res.code == 502) {
                                return location.replace('admin/login.html');
                            } else {
                                layer.msg(res.msg, {icon: 2});
                            }
                        }
                    });

                    if (data && data.openingPermit) {
                        $('#btnUpload15_path').html('<img src="' + data.openingPermit + '" style="height: 50px;" />');
                    }

                    //加载代理商分类
                    var arr2tree;
                    admin.req('enterprise/sell/admin/agentCategory/list', {limit: 99999}, function (res) {
                        for (let i = 0; i < res.data.length; i++) {
                            res.data[i].children = [];
                        }
                        arr2tree = xmSelect.arr2tree(res.data, "parentId", "id", "children", -1);
                    }, 'get', false);

                    var selectedData = function (treeData, targetId) {

                        for (var k = 0; k < treeData.length; k++) {
                            var nodeId = treeData[k].id;
                            if (targetId == nodeId) {
                                treeData[k].selected = true;
                                return;
                            } else {
                                if (treeData[k].children && treeData[k].children != '') {
                                    selectedData(treeData[k].children, targetId);
                                }
                            }
                        }
                    }

                    if (data) {
                        selectedData(arr2tree, data.agentCategoryId);
                    }

                    var smlSelectInstans = xmSelect.render({
                        el: '#agentCategoryId',
                        model: {label: {type: 'text'}},
                        radio: true,
                        clickClose: true,
                        filterable: true,
                        tree: {
                            show: true,
                            strict: false,
                            expandedKeys: [-1],
                        },
                        tips: '顶级分类',
                        prop: {
                            name: 'name',
                            value: 'id',
                            children: 'children'
                        },
                        data() {
                            //填充数据
                            return arr2tree;
                        },
                        on(data) {
                            let parentId = data.arr.length > 0 ? data.change[0].id : -1;
                            $("input[name='agentCategoryId']").val(parentId);
                        }
                    });

                    //加在代理商级别
                    admin.req('enterprise/sell/admin/agentLevel/list', {limit: 99999}, function (res) {
                        loadSelectHtml(res.data, "请选择代理商级别", "agtLevel", "name");
                        if (data) {
                            $("#agtLevel").val(data.agtLevel);
                            form.render('select');
                        }
                    }, 'get', false);

                    var selectArea = function (city) {
                        admin.req('enterprisecab/area/admin/area/getArea?parentId=' + city, {}, function (res) {
                            layer.closeAll('loading');
                            if (200 == res.code) {
                                $('#areaId').append(new Option("请选择区", ""));//往下拉菜单里添加元素
                                $.each(res.data, function (index, item) {
                                    $('#areaId').append(new Option(item.name, item.id));//往下拉菜单里添加元素
                                })
                                form.val('agentForm', data);
                                form.render(); //菜单渲染 把内容加载进去
                            } else {
                                layer.msg('获取(区县)区域信息失败!', {
                                    icon: 2,
                                    time: 1000
                                });
                            }
                        }, 'GET');
                    }

                    var selectCity = function (province) {
                        admin.req('enterprisecab/area/admin/area/getCity?parentId=' + province, {}, function (res) {
                            layer.closeAll('loading');
                            if (200 == res.code) {
                                $('#cityId').append(new Option("请选择市", ""));//往下拉菜单里添加元素
                                $.each(res.data, function (index, item) {
                                    $('#cityId').append(new Option(item.name, item.id));//往下拉菜单里添加元素
                                })
                                form.val('agentForm', data);
                                form.render(); //菜单渲染 把内容加载进去
                                if (data) {
                                    selectArea(data.cityId);
                                }
                            } else {
                                layer.msg('获取(市)区域信息失败!', {
                                    icon: 2,
                                    time: 1000
                                });
                            }
                        }, 'GET');
                    }
                    // 获取省区域信息
                    admin.req('enterprisecab/area/admin/area/getProvince', {}, function (res) {
                        layer.closeAll('loading');
                        if (200 == res.code) {
                            $('#provinceId').append(new Option("请选择省", ""));//往下拉菜单里添加元素
                            $.each(res.data, function (index, item) {
                                $('#provinceId').append(new Option(item.name, item.id));//往下拉菜单里添加元素
                            })

                            form.val('agentForm', data);
                            form.render(); //菜单渲染 把内容加载进去
                            if (data) {
                                selectCity(data.provinceId);
                            }
                        } else {
                            layer.msg('获取(省)区域信息失败!', {
                                icon: 2,
                                time: 1000
                            });
                        }
                    }, 'GET', true);

                    form.on('select(provinceId)', function (data) {
                        $("#cityId").empty();
                        $('#areaId').empty();

                        // 获取市区域信息
                        if (data.value != '') {
                            selectCity(data.value);
                        }
                    });

                    form.on('select(cityId)', function (data) {
                        $('#areaId').empty();

                        // 获取区县区域信息
                        if (data.value != '') {
                            selectArea(data.value);
                        }
                    });

                    if (data) {
                        var option = $("form select[name='sourceId']").find("option");
                        layui.each(option, function (index, item) {
                            if (data.sourceId == item.text) {
                                data.sourceId = item.value;
                            }
                        });
                    }

                    if (data) {
                        var option = $("form select[name='type']").find("option");
                        layui.each(option, function (index, item) {
                            if (data.type == item.text) {
                                data.type = item.value;
                            }
                        });
                    }

                    if (data) {
                        var option = $("form select[name='status']").find("option");
                        layui.each(option, function (index, item) {
                            if (data.status == item.text) {
                                data.status = item.value;
                            }
                        });
                    }

                    form.val('agentForm', data);
                    // 表单提交事件
                    form.on('submit(agentFormSubmit)', function (d) {
                        layer.load(2);
                        admin.req(data ? 'enterprise/sell/admin/agentApply/update' : 'enterprise/sell/admin/agentApply/add', d.field, function (res) {
                            layer.closeAll('loading');
                            if (res.code == 200) {
                                layer.msg(res.msg, {icon: 1});
                                table.reload('agentTable');
                                layer.closeAll('page');
                            } else {
                                layer.msg(res.msg, {icon: 2});
                            }
                        }, data ? 'PUT' : 'POST');
                        return false;
                    });
                }
            });
        }

        // 删除
        function doDelete(obj) {
            layer.confirm('确定要删除吗？', {
                offset: '65px',
                skin: 'layui-layer-admin'
            }, function (i) {
                layer.close(i);
                layer.load(2);
                admin.req('enterprise/sell/admin/agentApply/' + obj.data.id, {}, function (res) {
                    layer.closeAll('loading');
                    if (res.code == 200) {
                        layer.msg(res.msg, {icon: 1});
                        obj.del();
                    } else {
                        layer.msg(res.msg, {icon: 2});
                    }
                }, 'DELETE');
            });
        }

        // 审核
        function doCheck(obj) {
            layer.confirm('确定要审核吗？', {
                offset: '65px',
                skin: 'layui-layer-admin'
            }, function (i) {
                layer.close(i);
                layer.load(2);
                admin.req('enterprise/sell/admin/agentApply/check?agtId=' + obj.data.id, {}, function (res) {
                    layer.closeAll('loading');
                    if (res.code == 200) {
                        layer.msg(res.msg, {icon: 1});
                        table.reload('agentTable');
                    } else {
                        layer.msg(res.msg, {icon: 2});
                    }
                }, 'GET');
            });
        }

        // 尽调窗口
        function doSubjectList(obj) {
            admin.open({
                type: 1,
                area: ['85%', '85%'],
                offset: ['85px','265px'],
                title: '尽调管理',
                content: $('#dueForm').html(),
                success: function () {
                    doDue(obj);
                }
            })
        }

        //尽调
        function doDue(obj) {
            var dueFlag = true;

            table.render({
                elem: '#dueTable',
                url: config.base + 'enterprise/sell/admin/agentDue/list',
                where: {selAgtId: obj.data.id},
                page: true,
                cellMinWidth: 100,
                cols: [[
                    {type: 'numbers', title: '序号'}
                    , {field: 'code', align: 'center', title: '尽调编号'}
                    , {field: 'categoryName', align: 'center', title: '所属分类'}
                    , {field: 'subjectName', align: 'center', title: '科目名称'}
                    , {field: 'resultDesc', align: 'center', title: '尽调结果'}
                    , {field: 'statusDesc', align: 'center', title: '状态'}
                    , {field: 'createTime', align: 'center', title: '录入时间'}
                    , {field: 'auditor', align: 'center', title: '审核人'}
                    , {field: 'auditTime', align: 'center', title: '审核时间'}
                    , {align: 'center', toolbar: '#dueTableBar', title: '操作', width: 200}
                ]],
            });
            // 尽调添加按钮点击事件
            $('#dueBtnAdd').click(function () {
                dueFlag = false;
                showDueEditModel(obj);
            });


            // 显示编辑尽调弹窗
            function showDueEditModel(obj, data) {
                var index = admin.open({
                    type: 1,
                    area: ['80%', '80%'],
                    offset: ['105px','275px'],
                    title: data ? (dueFlag ? '修改尽调记录' : '详情') : '添加尽调记录',
                    content: $('#addDueForm').html(),
                    success: function () {

                        let agentAddDueTableData = [];

                        //加载尽调分类
                        var arr2tree;
                        admin.req('enterprise/sell/admin/agentDueSubjectCategory/list', {limit: 99999}, function (res) {
                            for (let i = 0; i < res.data.length; i++) {
                                res.data[i].children = [];
                            }
                            arr2tree = xmSelect.arr2tree(res.data, "parentId", "id", "children", -1);
                        }, 'get', false);

                        var selectedData = function (treeData, targetId) {
                            for (var k = 0; k < treeData.length; k++) {
                                var nodeId = treeData[k].id;
                                if (targetId == nodeId) {
                                    treeData[k].selected = true;
                                    return;
                                } else {
                                    if (treeData[k].children && treeData[k].children != '') {
                                        selectedData(treeData[k].children, targetId);
                                    }
                                }
                            }
                        };

                        if (data) {
                            selectedData(arr2tree, data.categoryId);
                            //加载尽调科目
                            admin.reqSync('enterprise/sell/admin/agentDueSubject/list', {
                                limit: 99999,
                                subId: data.categoryId
                            }, res => {
                                if (res.code === 200) {
                                    data.subjectIdData = res.data;
                                    res.data.forEach(item => {
                                        if (item.id == data.subjectId) {
                                            data.subjectDetailData = item.paramValue.split(',')
                                        }
                                    })
                                } else {
                                    data.subjectIdData = [];
                                    data.subjectDetailData = [];
                                }
                            }, 'get', false);
                            data.categoryIdData = arr2tree;
                            data.subjectDetailArr = [];
                            data.index = 0;
                            agentAddDueTableData = [data];

                        }


                        var agentAddDueTb = table.render({
                            elem: '#addDueTable',
                            data: agentAddDueTableData,
                            toolbar: data ? '' : '#addDueFormToolbar',
                            totalRow: false,
                            defaultToolbar: [],
                            page: false,
                            limit: Number.MAX_VALUE,
                            cellMinWidth: 100,
                            cols: [[
                                {
                                    field: 'categoryId',
                                    title: '尽调分类',
                                    templet: d => '<input type="hidden" id="categoryId' + d.index + '" /> <div class="categoryIdDataBox" id="categoryIdData' + d.index + '"></div>'
                                }
                                , {
                                    field: 'subjectId', title: '尽调科目', templet: d => {
                                        let selectHTML = '<select name="subjectId" lay-filter="subjectId" lay-verify="required">';
                                        selectHTML += '<option value="">请选择</option>';
                                        d.subjectIdData.forEach((item, index) => {
                                            if (item.id === d.subjectId) {
                                                selectHTML += `<option value="${item.id}" type="${item.type}" data="${item.paramValue}" selected="">${item.name}</option>`;
                                            } else {
                                                selectHTML += `<option value="${item.id}" type="${item.type}" data="${item.paramValue}">${item.name}</option>`;
                                            }
                                        });
                                        selectHTML += '</select>';
                                        return selectHTML
                                    }
                                }
                                , {
                                    field: 'subjectDetail', title: '尽调评述', width: 300, templet: d => {
                                        let subjectDetailHtml = '<div class="subjectDetailBox">';

                                        subjectDetailHtml += '<input type="text" class="layui-input subjectType" value="' + d.subjectDetail + '" lay-verify="required">'
                                        subjectDetailHtml += '</div>';
                                        return subjectDetailHtml
                                    }
                                }
                                , {
                                    field: 'enclosure',
                                    title: '附件', width: 80, align: 'center', templet: d => {
                                        let btnHTML = '';
                                        if (!data || dueFlag) {
                                            btnHTML += `<a class="layui-btn layui-btn-xs" lay-event="uploadEnclosure">${d.enclosure ? '更改附件' : '上传附件'}</a><br/>`;
                                        }
                                        if (d.enclosure) {
                                            btnHTML += '<a class="layui-btn layui-btn-xs layui-btn-warm" href="' + d.enclosure + '" target="view_window">查看附件</a>';
                                        }

                                        return btnHTML;
                                    }
                                }
                                , {
                                    field: 'result', title: '结果', templet: d => {
                                        let selectHTML = '<select name="result" lay-filter="result" lay-verify="required">';
                                        selectHTML += `<option value="pass" ${d.result == "pass" ? "selected" : ""}>符合且可以通过</option>`;
                                        selectHTML += `<option value="check" ${d.result == "check" ? "selected" : ""}>符合在考察考察</option>`;
                                        selectHTML += `<option value="waitPass" ${d.result == "waitPass" ? "selected" : ""}>不符合但可以通过</option>`;
                                        selectHTML += `<option value="inconformity" ${d.result == "inconformity" ? "selected" : ""}>不符合</option>`;
                                        selectHTML += '</select>';
                                        return selectHTML
                                    }
                                }
                                , {
                                    field: 'detail',
                                    title: '整体评估描述',
                                    templet: d => '<input type="text" name="detail" class="layui-input" value="' + d.detail + '">'
                                },
                                data ? "" : {align: 'center', toolbar: '#addDueTableBar', title: '操作', width: 100}
                            ]],
                            done: function (res, curr, count) {
                                if (count > 0) {
                                    $('button[lay-filter="addDueFormSubmit"]').show({duration: 300})
                                } else {
                                    $('button[lay-filter="addDueFormSubmit"]').hide({duration: 300})
                                }
                                for (let i = 0; i < res.data.length; i++) {
                                    xmSelect.render({
                                        el: '#categoryIdData' + agentAddDueTableData[i].index,
                                        model: {label: {type: 'text'}},
                                        radio: true,
                                        layVerify: 'required',
                                        initValue: [agentAddDueTableData[i].categoryId],
                                        disabled: data ? (dueFlag ? false : true) : false,
                                        clickClose: true,
                                        filterable: true,
                                        tree: {
                                            show: true,
                                            strict: false,
                                            expandedKeys: [-1],
                                        },
                                        tips: '尽调分类',
                                        prop: {
                                            name: 'name',
                                            value: 'id',
                                            children: 'children'
                                        },
                                        data() {
                                            //填充数据
                                            return JSON.parse(JSON.stringify(agentAddDueTableData[i].categoryIdData));
                                        },
                                        on(data) {
                                            let parentId = data.change[0].id || '';
                                            $("#categoryId" + i).val(parentId);

                                            agentAddDueTableData[i].categoryId = parentId;
                                            agentAddDueTableData[i].subjectType = '';
                                            agentAddDueTableData[i].subjectId = '';
                                            agentAddDueTableData[i].subjectDetail = '';
                                            //加载尽调科目
                                            admin.req('enterprise/sell/admin/agentDueSubject/list', {
                                                limit: 99999,
                                                subId: parentId
                                            }, function (res) {
                                                if (res.code === 200) {
                                                    agentAddDueTableData[i].subjectIdData = res.data;
                                                } else {
                                                    agentAddDueTableData[i].subjectIdData = [];
                                                }

                                                table.reload('addDueTable', {data: agentAddDueTableData});

                                            }, 'get', false);
                                        }
                                    });

                                    upload.render({
                                        elem: $('div[lay-id="addDueTable"]').find('[lay-event="uploadEnclosure"]').eq(i)
                                        , url: config.upload_url + 'uploadFile' //上传接口
                                        , data: {}
                                        , accept: 'file'
                                        , exts: 'jpg|png|RAR|zip|pdf|txt|doc|docx|xls|xlsx|ppt|pptx|apk'
                                        , headers: {Authorization: 'Bearer ' + config.getToken()}
                                        , done: function (res) {
                                            if (res.code == 200) {
                                                layer.msg(res.msg || "上传成功", {icon: 1});
                                                let imgObj = {
                                                    fileUrl: res.data.url,
                                                    fileName: res.data.fileName
                                                };
                                                agentAddDueTableData[this.elem.parents('tr').index()].enclosure = res.data.url;
                                                table.reload('addDueTable', {data: agentAddDueTableData});
                                            } else if (res.code == 502) {
                                                return location.replace('admin/login.html');
                                            } else {
                                                layer.msg(res.msg || "上传失败", {icon: 2});
                                            }
                                        }
                                    });


                                }
                                if (!dueFlag && data) {
                                    $('div[lay-id="addDueTable"] input').attr('disabled', 'disabled');
                                    $('div[lay-id="addDueTable"] select').attr('disabled', 'disabled');
                                    $('button[lay-filter="addDueFormSubmit"]').hide({duration: 300});
                                    form.render('select');
                                }
                            }
                        });

                        //监听头工具栏事件
                        table.on('toolbar(addDueTable)', function (_obj) {
                            let data = _obj.data;
                            if (_obj.event === 'addDueFormToolbarAdd') { //添加
                                let objData = {};
                                objData.index = agentAddDueTableData.length;
                                objData.selAgtId = obj.data.id;
                                objData.categoryIdData = arr2tree; // 尽调分类
                                objData.categoryId = ''; // 尽调分类

                                objData.subjectIdData = []; // 尽调科目
                                objData.subjectId = '';
                                objData.subjectType = '';


                                objData.subjectDetail = ''; // 尽调评述
                                objData.subjectDetailArr = []; // 复选框选择的值
                                objData.subjectDetailData = [];

                                objData.result = 'pass'; // 	结果
                                objData.resultData = '';// 结果数据

                                objData.enclosure = ''; // 	 附件
                                objData.detail = ''; // 整体评估描述
                                agentAddDueTableData.push(objData);
                                table.reload('addDueTable', {data: agentAddDueTableData});
                            }
                        });

                        // 工具条点击事件
                        table.on('tool(addDueTable)', function (obj) {
                            let data = obj.data;
                            if (obj.event === 'del') { // 删除
                                agentAddDueTableData.splice(obj.tr.index(), 1);
                                table.reload('addDueTable', {data: agentAddDueTableData});
                            }
                        });

                        form.on("select", function (data) {
                            if ($(data.elem).attr('name') == 'subjectId') {
                                if (data.value && data.value != '') {
                                    agentAddDueTableData[$(data.elem).parents('tr').index()].subjectId = data.value;
                                    //agentAddDueTableData[$(data.elem).parents('tr').index()].subjectType = $(data.elem).find("option:selected").attr("type");
                                    agentAddDueTableData[$(data.elem).parents('tr').index()].subjectDetailData = $(data.elem).find("option:selected").attr("data").split(',');
                                } else {
                                    agentAddDueTableData[$(data.elem).parents('tr').index()].subjectId = '';
                                    //agentAddDueTableData[$(data.elem).parents('tr').index()].subjectType = '';
                                    agentAddDueTableData[$(data.elem).parents('tr').index()].subjectDetailData = [];
                                }
                                agentAddDueTableData[$(data.elem).parents('tr').index()].subjectDetail = '';
                                table.reload('addDueTable', {data: agentAddDueTableData});
                            } else if ($(data.elem).attr('name') == 'result') {
                                agentAddDueTableData[$(data.elem).parents('tr').index()].result = data.value;
                            }
                        });


                        // 尽调评述 操作（输入文本框）
                        $("body").delegate("[lay-id='addDueTable'] .subjectDetailBox input.subjectType", "change", function () {
                            if (agentAddDueTableData[$(this).parents('tr').index()]) {
                                agentAddDueTableData[$(this).parents('tr').index()].subjectDetail = $(this).val().trim();

                            }
                        });

                        $("body").delegate("[lay-id='addDueTable'] input[name='detail']", "change", function () {
                            if (agentAddDueTableData[$(this).parents('tr').index()]) {
                                agentAddDueTableData[$(this).parents('tr').index()].detail = $(this).val().trim();
                            }
                        });

                        form.on('submit(addDueFormSubmit)', function (d) {
                            if (agentAddDueTableData.length == 0) {
                                layer.msg('请添加记录', {icon: 5});
                                return false;
                            }
                            admin.req(data ? 'enterprise/sell/admin/agentDue/update' : 'enterprise/sell/admin/agentDue/addList', data ? JSON.stringify(agentAddDueTableData[0]) : JSON.stringify(agentAddDueTableData), res => {
                                if (res.code === 200) {
                                    layer.msg(res.msg, {icon: 1});
                                    table.reload('dueTable');
                                    layer.close(index);
                                } else {
                                    layer.msg(res.msg, {icon: 2});
                                }
                            }, data ? 'PUT' : 'POST', true, 'application/json; charset=utf-8');
                            return false;
                        })
                    }

                })
            }

            //尽调工具条点击事件
            table.on('tool(dueTable)', function (obj) {
                var data = obj.data;
                if (obj.event === 'dueEdit') { //修改
                    dueFlag = true;
                    showDueEditModel(null, data);
                } else if (obj.event === 'dueDel') { // 删除
                    doDueDelete(obj);
                } else if (obj.event === 'dueCheck') { // 审核
                    doDueCheck(obj);
                } else if (obj.event === 'dueDetail') { // 详情
                    dueFlag = false;
                    showDueEditModel(null, data);
                }
            });

            // 尽调删除
            function doDueDelete(obj) {
                layer.confirm('确定要删除吗？', {
                    offset: '65px',
                    skin: 'layui-layer-admin'
                }, function (i) {
                    layer.close(i);
                    layer.load(2);
                    admin.req('enterprise/sell/admin/agentDue/' + obj.data.id, {}, function (res) {
                        layer.closeAll('loading');
                        if (res.code == 200) {
                            layer.msg(res.msg, {icon: 1});
                            obj.del();
                        } else {
                            layer.msg(res.msg, {icon: 2});
                        }
                    }, 'DELETE');
                });
            }

            // 尽调审核
            function doDueCheck(obj) {
                layer.confirm('确定要审核吗？', {
                    offset: '65px',
                    btn: ['通过', '不通过'],
                    skin: 'layui-layer-admin'
                }, function (i) {
                    layer.close(i);
                    layer.load(2);
                    admin.req('enterprise/sell/admin/agentDue/check', JSON.stringify({
                        id: obj.data.id,
                        status: 'pass'
                    }), res => {
                        layer.closeAll('loading');
                        if (res.code == 200) {
                            layer.msg(res.msg, {icon: 1});
                            table.reload('dueTable');
                            table.reload('agentTable');
                        } else {
                            layer.msg(res.msg, {icon: 2});
                        }
                    }, 'put', true, 'application/json; charset=utf-8');
                }, function (i) {
                    layer.close(i);
                    layer.load(2);
                    admin.req('enterprise/sell/admin/agentDue/check', JSON.stringify({
                        id: obj.data.id,
                        status: 'noPass'
                    }), res => {
                        layer.closeAll('loading');
                        if (res.code == 200) {
                            layer.msg(res.msg, {icon: 1});
                            table.reload('dueTable');
                            table.reload('agentTable');
                        } else {
                            layer.msg(res.msg, {icon: 2});
                        }
                    }, 'put', true, 'application/json; charset=utf-8');
                });
            }

            //自定义验证（单选、复选框）
            form.verify({
                otherReq: function (value, item) {
                    var verifyName = $(item).attr('name')
                        , verifyType = $(item).attr('type')
                        , formElem = $(item).parents('.layui-form')//获取当前所在的form元素，如果存在的话
                        , verifyElem = formElem.find("input[name='" + verifyName + "']")//获取需要校验的元素
                        , isTrue = verifyElem.is(':checked')//是否命中校验
                        , focusElem = verifyElem.next().find('i.layui-icon');//焦点元素
                    if (!isTrue || !value) {
                        //定位焦点
                        focusElem.css(verifyType == 'radio' ? {"color": "#FF5722"} : {"border-color": "#FF5722"});
                        //对非输入框设置焦点
                        focusElem.first().attr("tabIndex", "1").css("outline", "0").blur(function () {
                            focusElem.css(verifyType == 'radio' ? {"color": ""} : {"border-color": ""});
                        }).focus();
                        return '必填项不能为空';
                    }
                }
            });

        }

        // 导出excel
        $('#agentBtnExport').click(function () {
            var checkRows = table.checkStatus('agentTable');
            if (checkRows.data.length == 0) {
                layer.msg('请选择要导出的数据', {icon: 2});
            } else {
                table.exportFile(insTb.config.id, checkRows.data, 'xls');
            }
        });

    });
</script>